import time
import json
import paho.mqtt.client as mqtt
import rpi
import dht11
import sound
import ele


THINGSBOARD_SERVER = '43.143.141.18'
PORT = 1883
ACCESS_TOKEN = '3U0fClbRjIwu5c5QxVkP'

DHT11_GPIO = 17
sound_trig_pin = 19
sound_echo_pin = 18
ele_pin = 23





def on_message(client, userdata, msg):
    Msg = json.loads(msg.payload)
    switchLED = Msg['client']['power_LED']
    print("LED状态", switchLED)
    rpi.powerLed(switchLED)
    switchMotor = Msg['client']['songSwitch']
    print("电机状态", switchMotor)
    ele.startEle(ele_pin, (int(switchMotor)+1)%2)

    alterHumidity, alterTemperature = Msg['client']['alerthumidity'], Msg['client']['alerttemperature']
    humidity,temperature,distance =Msg['client']['humidity'], Msg['client']['temperature'], Msg['client']['distance']
    message = {'temperature': temperature, 'humidity': humidity, 'distance': distance, 'alterHumidity': alterHumidity, 'alterTemperature': alterTemperature}
    print("和警报信息一起上传",message)
    client.publish('v1/devices/me/attributes', json.dumps(message), 1)




client = mqtt.Client()
client.on_message = on_message
client.username_pw_set(ACCESS_TOKEN)
client.connect(THINGSBOARD_SERVER, PORT, 60)
client.loop_start()

client.subscribe('v1/devices/me/attributes/response/+')
print('subscribed')

while True:
    client.publish('v1/devices/me/attributes/request/1',
                   '{"clientKeys":"humidity,temperature,power_LED,songSwitch,alerthumidity,alerttemperature,distance"}')

    humidity, temperature = dht11.getDHT11(DHT11_GPIO)
    distance = sound.getDistance(sound_trig_pin, sound_echo_pin)
    message = {'temperature': temperature, 'humidity': humidity, 'distance': distance}
    print("当前温度：", temperature, "当前湿度：", humidity, "当前距离：", distance)
    client.publish('v1/devices/me/attributes', json.dumps(message), 1)
    
    time.sleep(1)


